import { getUserInfoApi, loginApi } from '@/api/user'
import router from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message } from 'element-ui'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  // 1、存token
  SET_TOKEN(state, token) {
    // 1.1 往本地存
    setToken(token)
    // 1.2 往state中存
    state.token = token
  },
  // 删除token
  REMOVE_TOKEN(state) {
    removeToken()
    state.token = null
  },

  // 设置用户信息
  SET_uSER_INFO(state, userInfo) {
    state.userInfo = userInfo
  },

  // 清空用户信息
  CLEAR_USER_INFO(state) {
    state.userInfo = {}
  }

}

const actions = {
  // user login
  async login(context, { mobile, password }) {
    // 登录发请求
    // const res = await axios.post('/cc/api/sys/login', { mobile, password })
    const token = await loginApi({ mobile, password })
    context.commit('SET_TOKEN', token)
    Message.success('登录成功~')
    // 登录跳转
    router.replace('/')
  },

  // user logout
  logout(context) {
    context.commit('REMOVE_TOKEN')
    context.commit('CLEAR_USER_INFO')
    // todo
  },

  // remove token

  // 设置用户信息
  async getUserInfo(context) {
    const userInfo = await getUserInfoApi()
    context.commit('SET_uSER_INFO', userInfo)
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

